<script setup lang="ts">
import {reactive, ref} from 'vue';
import {Card, Message} from '@arco-design/web-vue';
import {userLogin} from "@/api/userApi";
import router from "@/router";
import { Notification } from '@arco-design/web-vue';
import {getTime} from "@/utils/time";


// 当前激活的标签页
const activeKey = ref('account');

// 表单数据
const form = reactive({
  userAccount: '',
  userPassword: '',
  phone: '',
  code: ''
});

// 表单验证规则
const accountRules = {
  userAccount: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  userPassword: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      min: 8,
      message: '密码长度不能少于6位',
      trigger: 'blur'
    }
  ]
};

const phoneRules = {
  phone: [
    {
      required: true,
      message: '请输入手机号',
      trigger: 'blur'
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号格式',
      trigger: 'blur'
    }
  ],
  code: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    },
    {
      min: 6,
      max: 6,
      message: '验证码长度为6位',
      trigger: 'blur'
    }
  ]
};

// 状态管理
const isLoading = ref(false);
const showPassword = ref(false);
const formRef = ref();
const countdown = ref(0);

// 登录处理
const handleLogin = async () => {
  try {
    // 模拟登录请求
    isLoading.value = true;
    if (form.userAccount === '' || form.userPassword === '') {
      Message.error('用户名和密码不能为空');
      return;
    }
    console.log('登录信息:', form);
    const res = await userLogin(form);
    console.log(res.data)
    if (res.data.code === 0) {
      window.localStorage.setItem('user', JSON.stringify(res.data.data));
      window.localStorage.setItem('userRole', res.data.data.userRole);
      Message.success('登录成功');
/*      Notification.success({
        content: `${ getTime() } 好：欢迎回来，${ res.data.data.userAccount }！`,
        duration: 3,
        position: 'topRight',
      });*/
      // 这里可以添加跳转逻辑，例如使用 Vue Router 进行页面跳转
      await router.push('/home');
    } else {
      Message.error('登录失败');
    }
  } catch (error) {
    console.error('表单验证失败:', error);
    // Message.error('登录失败');
    isLoading.value = false;
  } finally {
    // 无论成功还是失败，重置表单验证状态
    formRef.value?.resetFields();
    isLoading.value = false;
  }
};

// 发送验证码
const sendCode = async () => {
  if (countdown.value > 0) return;

  // 简单验证手机号
  if (!form.phone || !/^1[3-9]\d{9}$/.test(form.phone)) {
    Message.error('请输入正确的手机号');
    return;
  }

  // 开始倒计时
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);

  // 模拟发送验证码请求
  console.log('发送验证码到:', form.phone);
  Message.success('验证码已发送，请注意查收');
};

// 切换密码显示状态
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};
</script>

<template>
  <div class="login-container">
    <a-spin :loading="isLoading">
      <!-- 登录卡片 -->
      <Card class="login-card arco-card-body" :bordered="false">
        <div class="login-header"></div>
        <div class="custom-tabs">
          <div class="center-tabs">
            <a-tabs class="arco-tabs-nav-tab-list" :default-active-key="activeKey">
              <a-tab-pane :key="activeKey" title="账号密码">
                <a-form ref="formRef" :rules="accountRules" :model="form" :style="{ width: '400px' }">
                  <div class="login-input">
                    <a-form-item field="userAccount" validate-trigger="blur">
                      <template #label>
                        账户：
                      </template>
                      <a-input v-model="form.userAccount" placeholder="请输入账户名："/>
                    </a-form-item>
                    <a-form-item field="userPassword" validate-trigger="blur">
                      <template #label>
                        密码：
                      </template>
                      <a-input-password v-model="form.userPassword" placeholder="请输入密码："/>
                    </a-form-item>
                  </div>
                  <div class="login-button" style="margin-top: 5px;">
                    <div style="display: flex; justify-content: space-between;   padding: 0 5px 0 5px">
                      <span><a>忘记密码？</a></span>
                      <span><RouterLink to="/user/register">注册账号</RouterLink></span>
                    </div>
                    <a-button style="width: 100%; font-size: 16px; margin-top: 10px;height: 40px;" type="primary" @click="handleLogin">登 录</a-button>
                  </div>

                </a-form>
              </a-tab-pane>
              <a-tab-pane key="phone" title="手机号码">
                <a-form :rules="phoneRules" :model="form" :style="{ width: '400px' }" type="submit"
                        @submit="handleLogin">
                  <div class="login-input">
                    <a-form-item field="phone" style="height: 40px" validate-trigger="blur">
                      <template #label>
                        <span style="font-size: 13px">手机号：</span>
                      </template>
                      <a-input v-model="form.phone" placeholder="请输入手机号"/>
                    </a-form-item>
                    <a-form-item field="code" validate-trigger="blur">
                      <template #label>
                        <span style="font-size: 13px">验证码：</span>
                      </template>
                      <a-input-search
                          placeholder="请输入验证码"
                          :button-text="countdown > 0 ? `${countdown}s后重新发送` : '发送验证码'"
                          search-button
                          v-model="form.code"
                          @search="sendCode"
                          :disabled="countdown > 0"
                      />
                    </a-form-item>
                  </div>
                  <div class="login-button" style="margin-top: 5px;">
                    <div style="display: flex; justify-content: space-between;  padding: 0 5px 0 5px">
                      <span><RouterLink to="/user/register">注册账号</RouterLink></span>
                    </div>
                    <a-button style="width: 100%; font-size: 16px; height: 40px;" type="primary" @click="handleLogin">登 录</a-button>
                  </div>

                </a-form>
              </a-tab-pane>
            </a-tabs>
          </div>
        </div>
      </Card>
    </a-spin>
  </div>
</template>

<style scoped>
.login-container {
  position: relative;
  min-height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('@/assets/login_bg.svg');
  background-size: cover;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  z-index: 0;
}

.login-card {
  width: 100%;
  height: 100%;
  max-width: 493px;
  max-height: 700px;
  margin-top: -100px;
  padding: 18px 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  background-color: rgba(255, 255, 255, 0.95);
}

.center-tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 10px; /* 与表单拉开点距离 */
  margin-top: 20px;
  height: 300px;
}

.arco-card-body:deep(.arco-card-body) {
  padding: 16px 25px;
}

.login-input {
  margin-left: 3px;
  margin-top: 10px;
}

.bottom-text {
  position: absolute;
  bottom: 0; /* 固定在底部 */
  left: 0;
  width: 100%;
  text-align: center;
  padding: 10px 0;
  background-color: #fff;
}

.arco-tabs-nav-tab-list::v-deep(.arco-tabs-nav-tab) {
  justify-content: center;
  width: 100%;
  transform: translateX(-5px);
}


</style>
